package com.cskaoyan.service;

import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserExample;
import com.cskaoyan.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author stone
 * @date 2021/11/29 15:17
 */
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    UserMapper userMapper;

    @Override
    public BaseData list(String username, String mobile, BaseParam param) {
        //在查询之前使用分页
        PageHelper.startPage(param.getPage(), param.getLimit());

        //List<User> users = userMapper.select(username, mobile, param.getSort(), param.getOrder());

        UserExample example = new UserExample();
        // 👉 List<Criterion> 条件列表
        //Criteria提供的and方法，就是向条件列表里塞入数据
//        example.createCriteria().andUsernameEqualTo(username).andMobileEqualTo(mobile);
        UserExample.Criteria criteria = example.createCriteria();
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (mobile != null && !"".equals(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<User> users = userMapper.selectByExample(example);
        //long total = userMapper.countByExample(example);
        //通过分页信息拿到分页数据
        //PageInfo的有参构造方法，放入的***查询结果***
        PageInfo info = new PageInfo(users);
        long total = info.getTotal();
        //total == users.size() 👉 false; 如果total小于等于limit是true
        //total ≥ users.size()
        return BaseData.list(users,total);
    }
}
